import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { 
  Users, 
  Package, 
  ShoppingCart, 
  DollarSign,
  Plus,
  Edit,
  Trash2,
  Eye,
  ArrowLeft
} from 'lucide-react';
import { 
  productApi, 
  categoryApi, 
  orderApi, 
  profileApi, 
  statsApi 
} from '@/db/api';
import { useAuth } from 'miaoda-auth-react';
import type { 
  Product, 
  Category, 
  Order, 
  Profile, 
  ProductFormData, 
  CategoryFormData 
} from '@/types/types';
import { toast } from 'sonner';

const AdminDashboard: React.FC = () => {
  const navigate = useNavigate();
  const { user } = useAuth();
  
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({
    total_products: 0,
    total_orders: 0,
    total_users: 0,
    total_revenue: 0,
    recent_orders: [] as Order[]
  });
  
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [orders, setOrders] = useState<Order[]>([]);
  const [users, setUsers] = useState<Profile[]>([]);
  
  const [isProductDialogOpen, setIsProductDialogOpen] = useState(false);
  const [isCategoryDialogOpen, setIsCategoryDialogOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);

  const [productForm, setProductForm] = useState<ProductFormData>({
    name: '',
    description: '',
    price: 0,
    original_price: 0,
    category_id: '',
    images: [],
    sizes: [],
    colors: [],
    stock: 0,
    is_featured: false,
    is_active: true
  });

  const [categoryForm, setCategoryForm] = useState<CategoryFormData>({
    name: '',
    description: '',
    image_url: '',
    sort_order: 0
  });

  useEffect(() => {
    checkAdminAccess();
  }, [user, navigate]);

  const checkAdminAccess = async () => {
    if (!user) {
      navigate('/login');
      return;
    }

    try {
      const profile = await profileApi.getCurrentProfile();
      if (!profile || profile.role !== 'admin') {
        toast.error('您没有管理员权限');
        navigate('/');
        return;
      }
      loadData();
    } catch (error) {
      console.error('检查权限失败:', error);
      navigate('/');
    }
  };

  const loadData = async () => {
    try {
      setLoading(true);
      const [
        statsData,
        productsData,
        categoriesData,
        ordersData,
        usersData
      ] = await Promise.all([
        statsApi.getDashboardStats(),
        productApi.getAllProducts(),
        categoryApi.getCategories(),
        orderApi.getAllOrders(),
        profileApi.getAllProfiles()
      ]);

      setStats(statsData);
      setProducts(productsData);
      setCategories(categoriesData);
      setOrders(ordersData);
      setUsers(usersData);
    } catch (error) {
      console.error('加载数据失败:', error);
      toast.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCreateProduct = async () => {
    try {
      const newProduct = await productApi.createProduct(productForm);
      setProducts(prev => [newProduct, ...prev]);
      setIsProductDialogOpen(false);
      resetProductForm();
      toast.success('商品创建成功');
    } catch (error) {
      console.error('创建商品失败:', error);
      toast.error('创建商品失败');
    }
  };

  const handleUpdateProduct = async () => {
    if (!editingProduct) return;
    
    try {
      const updatedProduct = await productApi.updateProduct(editingProduct.id, productForm);
      setProducts(prev => prev.map(p => p.id === editingProduct.id ? updatedProduct : p));
      setIsProductDialogOpen(false);
      setEditingProduct(null);
      resetProductForm();
      toast.success('商品更新成功');
    } catch (error) {
      console.error('更新商品失败:', error);
      toast.error('更新商品失败');
    }
  };

  const handleDeleteProduct = async (id: string) => {
    if (!confirm('确定要删除这个商品吗？')) return;
    
    try {
      await productApi.deleteProduct(id);
      setProducts(prev => prev.filter(p => p.id !== id));
      toast.success('商品删除成功');
    } catch (error) {
      console.error('删除商品失败:', error);
      toast.error('删除商品失败');
    }
  };

  const handleCreateCategory = async () => {
    try {
      const newCategory = await categoryApi.createCategory(categoryForm);
      setCategories(prev => [...prev, newCategory]);
      setIsCategoryDialogOpen(false);
      resetCategoryForm();
      toast.success('分类创建成功');
    } catch (error) {
      console.error('创建分类失败:', error);
      toast.error('创建分类失败');
    }
  };

  const handleUpdateCategory = async () => {
    if (!editingCategory) return;
    
    try {
      const updatedCategory = await categoryApi.updateCategory(editingCategory.id, categoryForm);
      setCategories(prev => prev.map(c => c.id === editingCategory.id ? updatedCategory : c));
      setIsCategoryDialogOpen(false);
      setEditingCategory(null);
      resetCategoryForm();
      toast.success('分类更新成功');
    } catch (error) {
      console.error('更新分类失败:', error);
      toast.error('更新分类失败');
    }
  };

  const handleDeleteCategory = async (id: string) => {
    if (!confirm('确定要删除这个分类吗？')) return;
    
    try {
      await categoryApi.deleteCategory(id);
      setCategories(prev => prev.filter(c => c.id !== id));
      toast.success('分类删除成功');
    } catch (error) {
      console.error('删除分类失败:', error);
      toast.error('删除分类失败');
    }
  };

  const handleUpdateOrderStatus = async (orderId: string, status: Order['status']) => {
    try {
      await orderApi.updateOrderStatus(orderId, status);
      setOrders(prev => prev.map(o => o.id === orderId ? { ...o, status } : o));
      toast.success('订单状态更新成功');
    } catch (error) {
      console.error('更新订单状态失败:', error);
      toast.error('更新订单状态失败');
    }
  };

  const handleUpdateUserRole = async (userId: string, role: 'user' | 'admin') => {
    try {
      await profileApi.updateUserRole(userId, role);
      setUsers(prev => prev.map(u => u.user_id === userId ? { ...u, role } : u));
      toast.success('用户角色更新成功');
    } catch (error) {
      console.error('更新用户角色失败:', error);
      toast.error('更新用户角色失败');
    }
  };

  const resetProductForm = () => {
    setProductForm({
      name: '',
      description: '',
      price: 0,
      original_price: 0,
      category_id: '',
      images: [],
      sizes: [],
      colors: [],
      stock: 0,
      is_featured: false,
      is_active: true
    });
  };

  const resetCategoryForm = () => {
    setCategoryForm({
      name: '',
      description: '',
      image_url: '',
      sort_order: 0
    });
  };

  const openProductDialog = (product?: Product) => {
    if (product) {
      setEditingProduct(product);
      setProductForm({
        name: product.name,
        description: product.description || '',
        price: product.price,
        original_price: product.original_price || 0,
        category_id: product.category_id || '',
        images: product.images || [],
        sizes: product.sizes || [],
        colors: product.colors || [],
        stock: product.stock,
        is_featured: product.is_featured,
        is_active: product.is_active
      });
    } else {
      setEditingProduct(null);
      resetProductForm();
    }
    setIsProductDialogOpen(true);
  };

  const openCategoryDialog = (category?: Category) => {
    if (category) {
      setEditingCategory(category);
      setCategoryForm({
        name: category.name,
        description: category.description || '',
        image_url: category.image_url || '',
        sort_order: category.sort_order
      });
    } else {
      setEditingCategory(null);
      resetCategoryForm();
    }
    setIsCategoryDialogOpen(true);
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-pink-600"></div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header */}
        <div className="flex items-center gap-4 mb-8">
          <Button variant="ghost" onClick={() => navigate('/')}>
            <ArrowLeft className="h-5 w-5 mr-2" />
            返回首页
          </Button>
          <h1 className="text-3xl font-bold text-gray-900">管理后台</h1>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">总商品数</p>
                  <p className="text-3xl font-bold text-gray-900">{stats.total_products}</p>
                </div>
                <Package className="h-8 w-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">总订单数</p>
                  <p className="text-3xl font-bold text-gray-900">{stats.total_orders}</p>
                </div>
                <ShoppingCart className="h-8 w-8 text-green-600" />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">总用户数</p>
                  <p className="text-3xl font-bold text-gray-900">{stats.total_users}</p>
                </div>
                <Users className="h-8 w-8 text-purple-600" />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">总收入</p>
                  <p className="text-3xl font-bold text-gray-900">¥{stats.total_revenue.toFixed(2)}</p>
                </div>
                <DollarSign className="h-8 w-8 text-pink-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Management Tabs */}
        <Tabs defaultValue="products" className="space-y-6">
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="products">商品管理</TabsTrigger>
            <TabsTrigger value="categories">分类管理</TabsTrigger>
            <TabsTrigger value="orders">订单管理</TabsTrigger>
            <TabsTrigger value="users">用户管理</TabsTrigger>
          </TabsList>

          {/* Products Management */}
          <TabsContent value="products">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle>商品管理</CardTitle>
                  <Dialog open={isProductDialogOpen} onOpenChange={setIsProductDialogOpen}>
                    <DialogTrigger asChild>
                      <Button onClick={() => openProductDialog()}>
                        <Plus className="h-4 w-4 mr-2" />
                        添加商品
                      </Button>
                    </DialogTrigger>
                    <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
                      <DialogHeader>
                        <DialogTitle>
                          {editingProduct ? '编辑商品' : '添加商品'}
                        </DialogTitle>
                      </DialogHeader>
                      <div className="space-y-4">
                        <div className="grid grid-cols-2 gap-4">
                          <div>
                            <Label htmlFor="product-name">商品名称</Label>
                            <Input
                              id="product-name"
                              value={productForm.name}
                              onChange={(e) => setProductForm(prev => ({ ...prev, name: e.target.value }))}
                            />
                          </div>
                          <div>
                            <Label htmlFor="product-category">分类</Label>
                            <Select
                              value={productForm.category_id}
                              onValueChange={(value) => setProductForm(prev => ({ ...prev, category_id: value }))}
                            >
                              <SelectTrigger>
                                <SelectValue placeholder="选择分类" />
                              </SelectTrigger>
                              <SelectContent>
                                {categories.map((category) => (
                                  <SelectItem key={category.id} value={category.id}>
                                    {category.name}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                        </div>

                        <div>
                          <Label htmlFor="product-description">商品描述</Label>
                          <Textarea
                            id="product-description"
                            value={productForm.description}
                            onChange={(e) => setProductForm(prev => ({ ...prev, description: e.target.value }))}
                          />
                        </div>

                        <div className="grid grid-cols-3 gap-4">
                          <div>
                            <Label htmlFor="product-price">价格</Label>
                            <Input
                              id="product-price"
                              type="number"
                              value={productForm.price}
                              onChange={(e) => setProductForm(prev => ({ ...prev, price: Number(e.target.value) }))}
                            />
                          </div>
                          <div>
                            <Label htmlFor="product-original-price">原价</Label>
                            <Input
                              id="product-original-price"
                              type="number"
                              value={productForm.original_price}
                              onChange={(e) => setProductForm(prev => ({ ...prev, original_price: Number(e.target.value) }))}
                            />
                          </div>
                          <div>
                            <Label htmlFor="product-stock">库存</Label>
                            <Input
                              id="product-stock"
                              type="number"
                              value={productForm.stock}
                              onChange={(e) => setProductForm(prev => ({ ...prev, stock: Number(e.target.value) }))}
                            />
                          </div>
                        </div>

                        <div className="flex gap-4">
                          <Button
                            onClick={editingProduct ? handleUpdateProduct : handleCreateProduct}
                            className="flex-1"
                          >
                            {editingProduct ? '更新商品' : '创建商品'}
                          </Button>
                          <Button
                            variant="outline"
                            onClick={() => setIsProductDialogOpen(false)}
                          >
                            取消
                          </Button>
                        </div>
                      </div>
                    </DialogContent>
                  </Dialog>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {products.map((product) => (
                    <div key={product.id} className="flex items-center justify-between p-4 border rounded-lg">
                      <div className="flex items-center gap-4">
                        <img
                          src={product.images?.[0] || 'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=100'}
                          alt={product.name}
                          className="w-16 h-16 object-cover rounded"
                        />
                        <div>
                          <h3 className="font-semibold">{product.name}</h3>
                          <p className="text-sm text-gray-600">{product.category?.name}</p>
                          <div className="flex items-center gap-2 mt-1">
                            <span className="text-pink-600 font-medium">¥{product.price}</span>
                            <span className="text-sm text-gray-500">库存: {product.stock}</span>
                            {product.is_featured && (
                              <Badge variant="secondary">推荐</Badge>
                            )}
                            {!product.is_active && (
                              <Badge variant="destructive">下架</Badge>
                            )}
                          </div>
                        </div>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => openProductDialog(product)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleDeleteProduct(product.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Categories Management */}
          <TabsContent value="categories">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle>分类管理</CardTitle>
                  <Dialog open={isCategoryDialogOpen} onOpenChange={setIsCategoryDialogOpen}>
                    <DialogTrigger asChild>
                      <Button onClick={() => openCategoryDialog()}>
                        <Plus className="h-4 w-4 mr-2" />
                        添加分类
                      </Button>
                    </DialogTrigger>
                    <DialogContent>
                      <DialogHeader>
                        <DialogTitle>
                          {editingCategory ? '编辑分类' : '添加分类'}
                        </DialogTitle>
                      </DialogHeader>
                      <div className="space-y-4">
                        <div>
                          <Label htmlFor="category-name">分类名称</Label>
                          <Input
                            id="category-name"
                            value={categoryForm.name}
                            onChange={(e) => setCategoryForm(prev => ({ ...prev, name: e.target.value }))}
                          />
                        </div>
                        <div>
                          <Label htmlFor="category-description">分类描述</Label>
                          <Textarea
                            id="category-description"
                            value={categoryForm.description}
                            onChange={(e) => setCategoryForm(prev => ({ ...prev, description: e.target.value }))}
                          />
                        </div>
                        <div>
                          <Label htmlFor="category-sort">排序</Label>
                          <Input
                            id="category-sort"
                            type="number"
                            value={categoryForm.sort_order}
                            onChange={(e) => setCategoryForm(prev => ({ ...prev, sort_order: Number(e.target.value) }))}
                          />
                        </div>
                        <div className="flex gap-4">
                          <Button
                            onClick={editingCategory ? handleUpdateCategory : handleCreateCategory}
                            className="flex-1"
                          >
                            {editingCategory ? '更新分类' : '创建分类'}
                          </Button>
                          <Button
                            variant="outline"
                            onClick={() => setIsCategoryDialogOpen(false)}
                          >
                            取消
                          </Button>
                        </div>
                      </div>
                    </DialogContent>
                  </Dialog>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {categories.map((category) => (
                    <div key={category.id} className="flex items-center justify-between p-4 border rounded-lg">
                      <div>
                        <h3 className="font-semibold">{category.name}</h3>
                        <p className="text-sm text-gray-600">{category.description}</p>
                        <p className="text-xs text-gray-500">排序: {category.sort_order}</p>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => openCategoryDialog(category)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleDeleteCategory(category.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Orders Management */}
          <TabsContent value="orders">
            <Card>
              <CardHeader>
                <CardTitle>订单管理</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {orders.map((order) => (
                    <div key={order.id} className="p-4 border rounded-lg">
                      <div className="flex items-center justify-between mb-2">
                        <div>
                          <h3 className="font-semibold">订单号: {order.order_number}</h3>
                          <p className="text-sm text-gray-600">
                            下单时间: {new Date(order.created_at).toLocaleString()}
                          </p>
                        </div>
                        <div className="text-right">
                          <p className="font-semibold text-pink-600">¥{order.total_amount.toFixed(2)}</p>
                          <Select
                            value={order.status}
                            onValueChange={(value) => handleUpdateOrderStatus(order.id, value as Order['status'])}
                          >
                            <SelectTrigger className="w-32">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="pending">待付款</SelectItem>
                              <SelectItem value="paid">已付款</SelectItem>
                              <SelectItem value="shipped">已发货</SelectItem>
                              <SelectItem value="delivered">已完成</SelectItem>
                              <SelectItem value="cancelled">已取消</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                      <div className="text-sm text-gray-600">
                        共 {order.order_items?.reduce((sum, item) => sum + item.quantity, 0)} 件商品
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Users Management */}
          <TabsContent value="users">
            <Card>
              <CardHeader>
                <CardTitle>用户管理</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {users.map((user) => (
                    <div key={user.id} className="flex items-center justify-between p-4 border rounded-lg">
                      <div>
                        <h3 className="font-semibold">{user.nickname || '未设置昵称'}</h3>
                        <p className="text-sm text-gray-600">{user.phone}</p>
                        <p className="text-xs text-gray-500">
                          注册时间: {new Date(user.created_at).toLocaleDateString()}
                        </p>
                      </div>
                      <div className="flex items-center gap-2">
                        <Badge variant={user.role === 'admin' ? 'default' : 'secondary'}>
                          {user.role === 'admin' ? '管理员' : '普通用户'}
                        </Badge>
                        <Select
                          value={user.role}
                          onValueChange={(value) => handleUpdateUserRole(user.user_id, value as 'user' | 'admin')}
                        >
                          <SelectTrigger className="w-32">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="user">普通用户</SelectItem>
                            <SelectItem value="admin">管理员</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
};

export default AdminDashboard;